<template>
  <gg-form-item :label="label" :labelWidth="localLabelWidth" :layout="localLayout" :tip="tip">
    <switch class="gg-switch-switch" :disabled="disabled" name="checked" :checked="checked" @change="handleChange" />
  </gg-form-item>
</template>

<script>
import MixinsCommon from '../mixins/mixins-common.js';
export default {
  mixins: [MixinsCommon],
  name: "GgSwitch",
  inject: {
    ggFormGroup: {
      default() {
        return null
      }
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    //默认输入框内容
    value: {
      type: [String, Number, Boolean],
      default: 0
    }

  },
  data() {
    return {
      localVal: 0,
      itemsValue: '',
      dataType: 'Number',
      checked: false,
    };
  },
  watch: {
    value(newVal) {
      this._dealDataList();
    }
  },
  created: function () {
    this._dealDataList();
  },
  methods: {
    /* 整理数据 */
    _dealDataList: function () {
      this.dataType = typeof this.value;
      switch (this.dataType) {
        case 'boolean':
          this.checked = this.value;
          break;
        case 'number':
          if (this.value === 1) {
            this.checked = true;
          } else {
            this.checked = false;
          }
          break;
        case 'string':
          if (this.value === '1') {
            this.checked = true;
          } else {
            this.checked = false;
          }
          break;
      }
    },
    handleChange: function (e) {
      this.checked = e.detail.value;
      this.updateInput();
    },
    updateInput() {
      switch (this.dataType) {
        case 'boolean':
          this.localVal = this.checked
          break;
        case 'number':
          if (this.checked == true) {
            this.localVal = 1;
          } else {
            this.localVal = 0;
          }
          break;
        case 'string':
          if (this.checked == true) {
            this.localVal = '1';
          } else {
            this.localVal = '0';
          }
          break;
      }
      this.$emit('input', this.localVal);
    }
  }
};
</script>

<style>
.gg-switch-switch {
  transform: scale(0.7);
  position: absolute;
  right: 2px;
}
</style>
